package com.fire.control.system.module.login.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fire.control.system.config.redis.RedisService;
import com.fire.control.system.dto.CompanyDTO;
import com.fire.control.system.dto.LoginResultDTO;
import com.fire.control.system.dto.ResourceDTO;
import com.fire.control.system.dto.UserDTO;
import com.fire.control.system.entity.Role;
import com.fire.control.system.entity.User;
import com.fire.control.system.module.login.dao.LoginMapper;
import com.fire.control.system.module.login.service.ILoginService;
import com.fire.control.system.module.role.dao.RoleMapper;
import com.fire.control.system.module.role.service.IRoleService;
import com.fire.control.system.module.user.dao.UserRepository;
import com.fire.control.system.statics.Key;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.support.protocol.comman.ProtocolSelector;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.protocol.login.LoginRequestProtocol;
import com.fire.control.system.support.util.ResourceTreeUtil;
import com.fire.control.system.support.util.SmsUtil;
import com.fire.control.system.support.util.XdaoDate;
import com.fire.control.system.support.util.XdaoPassword;

/**
 * @author liuxincheng
 * @ClassName: LoginServiceImpl
 * @Description: TODO(登陆业务层实现)
 * @author A18ccms a18ccms_gmail_com
 * @date 2017年5月5日 上午11:16:40
 */
@Service("loginService")
public class LoginServiceImpl implements ILoginService {
	public static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private ProtocolSelector protocolSelector;

	@Autowired
	private SmsUtil loginUtil;

	@Autowired
	private RedisService redisService;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private LoginMapper loginMapper;
	
	@Autowired
	private IRoleService roleService;

	/**
	 * 验证码
	 */
	private String idenCode;

	private String phoneNumber;

	/**
	 * <p>
	 * Title: jumpToLoginPage
	 * </p>
	 * <p>
	 * Description: WEB端--------跳到验证码登陆页面
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.login.service.ILoginService#jumpToLoginPage(com.fire.control.system.support.protocol.login.LoginRequestProtocol)
	 */
	@Override
	public ResponseProtocol jumpToLoginPage(LoginRequestProtocol requestProtocol,HttpServletRequest request) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		idenCode = XdaoPassword.getRandomCode();

		if (!idenCode.equals(null)) {
			response.setDate(new XdaoDate());
			response.setData(idenCode);
			redisService.set(Key.idenCode.toString()+request.getSession().getId(), idenCode, 180);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("验证码生成成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("验证码生成失败!");
			response.setDate(new XdaoDate());
			response.setData(null);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: login
	 * </p>
	 * <p>
	 * Description:WEB端--------账号+验证码登陆
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.login.service.ILoginService#login(com.fire.control.system.support.protocol.login.LoginRequestProtocol)
	 */
	@Override
	public ResponseProtocol loginByIdenCode(LoginRequestProtocol requestProtocol,HttpServletRequest request) {
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		if(StringUtils.isEmpty(requestProtocol.getLoginName())){
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("用户名不能为空!");
			return response;
		}
		if(StringUtils.isEmpty(requestProtocol.getPassword())){
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("密码不能为空!");
			return response;
		}
		if(StringUtils.isEmpty(requestProtocol.getIdenCode())){
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("验证码不能为空!");
			return response;
		}
		this.checkLoginInfoByUser(requestProtocol, request,response);
		return response;
	}

	/**
	 * @author liuxincheng
	 * @Title: isNull
	 * @Description: TODO(是否为空判断)
	 * @param @param
	 *            requestProtocol
	 * @param @return
	 *            设定文件
	 * @return boolean 返回类型
	 * @throws null
	 */
	private boolean isNull(LoginRequestProtocol requestProtocol) {
		if (requestProtocol.getType() == null || requestProtocol.getLoginName() == null
				|| requestProtocol.getPassword() == null) {
			return true;
		}
		return false;
	}

	/**
	 * @author liuxincheng
	 * @Title: checkLoginInfoByUser
	 * @Description: TODO(WEB端-----账号+验证码验证)
	 * @param @param
	 *            requestProtocol
	 * @param @param
	 *            response 设定文件
	 * @return void 返回类型
	 * @throws null
	 */
	public void checkLoginInfoByUser(LoginRequestProtocol requestProtocol,HttpServletRequest request, ResponseProtocol response) {
		String loginName = requestProtocol.getLoginName();
		String password = requestProtocol.getPassword();
		String inputIdencode = requestProtocol.getIdenCode();
		String idenCode = redisService.get(Key.idenCode.toString()+request.getSession().getId());
		// String converPwd = XdaoPassword.getXdaoPassword(loginName, password);
		//验证码验证不区分大小写
		if (inputIdencode.toLowerCase().equals(idenCode.toLowerCase())) {
			User user = userRepository.findByLoginNameAndPassword(loginName);
			if (user == null) {
				ResponseMessage.CODE_400.messageToProtocol(response).setMessage("用户不存在!");
				return;
			}
			
			List<String> roleIds = new ArrayList<String>();
			
			for(Role r : user.getRole()){
				roleIds.add(r.getId());
			}
			//勿删
			List<ResourceDTO> resourceList = new ArrayList<ResourceDTO>();
			if(roleIds!=null && !roleIds.isEmpty()){
				resourceList = ResourceTreeUtil.resourceTree(roleService.getResourceByRoleId(roleIds));				
			}
			
			LoginResultDTO result = new LoginResultDTO();
			if (password.equals(XdaoPassword.decrypt(user.getPassword()))) {
				UserDTO userDTO = new UserDTO();
				userDTO.setUser(user);
				userDTO.setCompany(user.getCompany());
				userDTO.setRole(roleMapper.getRoleByUserId(user.getId()));
				userDTO.setResourceList(resourceList);

				result.setUserDTO(userDTO);
				CompanyDTO companyDTO = new CompanyDTO();
				companyDTO.setCompany(user.getCompany());
				result.setCompany(companyDTO);
				
				response.setData(result);
				ResponseMessage.CODE_200.messageToProtocol(response).setMessage("登陆成功!");
			} else {
				ResponseMessage.CODE_400.messageToProtocol(response).setMessage("用户名或密码错误!");
			}
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("验证码错误!");
		}
	}

	/**
	 * <p>Title: loginOut</p>
	 * <p>Description: 登出系统</p>
	 * @param requestProtocol
	 * @param user
	 * @return
	 * @see com.fire.control.system.module.login.service.ILoginService#loginOut(com.fire.control.system.support.protocol.login.LoginRequestProtocol, com.fire.control.system.dto.UserDTO)
	 */
	@Override
	public ResponseProtocol loginOut(LoginRequestProtocol requestProtocol, UserDTO user,HttpServletRequest request) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(0);
		ResponseMessage.CODE_200.messageToProtocol(response).setMessage("退出系统成功!");
		return response;
	}
	/*
	 * public void checkLoginInfoByCompany(LoginRequestProtocol requestProtocol,
	 * ResponseProtocol response) {
	 * 
	 * String loginName = requestProtocol.getLoginName(); String password =
	 * requestProtocol.getPassword();
	 * 
	 * // String converPwd = XdaoPassword.getXdaoPassword(loginName, password);
	 * 
	 * Company company = companyRepository.findByLoginNameAndPassword(loginName,
	 * password); if (company == null) {
	 * Message_Response.LOGIN_ERROR_USER_NULL.messageToProtocol(response);
	 * return; }
	 * 
	 * LoginResultDTO result = new LoginResultDTO(); CompanyDTO companyDTO = new
	 * CompanyDTO(); companyDTO.setCompany(company);
	 * result.setCompany(companyDTO);
	 * result.setResourceList(resourceTreeUtil.getRoleResources(company.getRoles
	 * ())); response.setData(result);
	 * ResponseMessage.CODE_200.messageToProtocol(response); }
	 */

	/**********************************
	 * APP端-登陆
	 **************************************/
	/**
	 * <p>
	 * Title: loginByAccount
	 * </p>
	 * <p>
	 * Description:APP端--------账号登陆
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.login.service.ILoginService#loginByAccount(com.fire.control.system.support.protocol.login.LoginRequestProtocol)
	 */
	@Override
	public ResponseProtocol loginByAccount(LoginRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		response.setTaskuuid(requestProtocol.getTaskuuid());

		String loginName = requestProtocol.getLoginName();
		String password = requestProtocol.getPassword();
		User user = userRepository.findByLoginNameAndPassword(loginName);

		LoginResultDTO loginResultDTO = null;
		if (user == null) {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("用户为空!");
			return response;
		} else {

			loginResultDTO = new LoginResultDTO();
            String pwd = XdaoPassword.decrypt(user.getPassword());
			if (password.equals(pwd)) {
				UserDTO userDTO = new UserDTO();
				userDTO.setUser(user);
				userDTO.setCompany(user.getCompany());
				userDTO.setRole(roleMapper.getRoleByUserId(user.getId()));

				loginResultDTO.setUser(user);

				response.setData(loginResultDTO);
				ResponseMessage.CODE_200.messageToProtocol(response).setMessage("登陆成功!");
			} else {
				ResponseMessage.CODE_400.messageToProtocol(response).setMessage("密码输入错误!");
			}
			return response;
		}
	}

	/**
	 * <p>
	 * Title: LoginBySms
	 * </p>
	 * <p>
	 * Description: APP端-------短信验证验证码登陆
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.login.service.ILoginService#LoginBySms(com.fire.control.system.support.protocol.login.LoginRequestProtocol)
	 */
	@Override
	public ResponseProtocol LoginBySms(LoginRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		String inputCode = requestProtocol.getIdenCode();
		String phoneNumber = requestProtocol.getPhoneNumber();
		String idencode = redisService.get(Key.idenCode + phoneNumber);
		String telPhone = redisService.get(Key.redis_key_lora_phoneNumber + phoneNumber);

		LoginResultDTO loginResultDTO = null;
		UserDTO userDTO = null;
		if (phoneNumber != null && phoneNumber.equals(telPhone)) {
			if (inputCode != null && inputCode.equals(idencode)) {
				loginResultDTO = new LoginResultDTO();
				userDTO = new UserDTO();
				User u = loginMapper.getUserByTelphone(phoneNumber);

				User user = userRepository.findOne(u.getId());
				userDTO.setUser(user);

				userDTO.setCompany(user.getCompany());
				userDTO.setRole(roleMapper.getRoleByUserId(u.getId()));

				loginResultDTO.setUser(user);

				ResponseMessage.CODE_200.messageToProtocol(response).setMessage("登陆成功!");
				
				response.setDate(new XdaoDate());
				response.setData(loginResultDTO);
			} else {
				ResponseMessage.CODE_400.messageToProtocol(response).setMessage("验证码错误!");
				response.setDate(new XdaoDate());
			}

		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("电话号码登陆失败!");
			response.setDate(new XdaoDate());
		}
		return response;
	}

	/**
	 * <p>Title: loginOutApp</p>
	 * <p>Description: APP端------>退出APP</p>
	 * @param requestProtocol
	 * @param user
	 * @param request
	 * @return
	 * @see com.fire.control.system.module.login.service.ILoginService#loginOutApp(com.fire.control.system.support.protocol.login.LoginRequestProtocol, com.fire.control.system.dto.UserDTO, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public ResponseProtocol loginOutApp(LoginRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		boolean flag = redisService.expire(Key.redis_key_lora_user_id_ + user.getUserId(), 0);
		
		if(flag){
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("退出系统成功!");
		}else{
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("退出系统失败!");
		}
		return response;
	}
	/************************************** APP与WEB端共用的发送短信接口 ***********************************************/
	/**
	 * <p>
	 * Title: SendSms
	 * </p>
	 * <p>
	 * Description:发送验证码
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.login.service.ILoginService#loginBySms(com.fire.control.system.support.protocol.login.LoginRequestProtocol)
	 */
	@Override
	public ResponseProtocol SendSms(LoginRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		boolean flag = false;
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		phoneNumber = requestProtocol.getPhoneNumber();

		// 发送验证码
		idenCode = XdaoPassword.getRandomCode();

		flag = loginUtil.sendSmsCode(phoneNumber, idenCode);

		if (flag) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("验证码发送成功!");
			response.setDate(new XdaoDate());
			redisService.set(Key.idenCode + phoneNumber, idenCode, Key.idenCode.getExpire());
			redisService.set(Key.redis_key_lora_phoneNumber + phoneNumber, phoneNumber,
					Key.redis_key_lora_phoneNumber.getExpire());
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("验证码发送失败!");
			response.setDate(new XdaoDate());
		}
		return response;
	}
}
